<?php

namespace app\common\service;
use app\common\library\easywechat\AppWx;
use think\facade\Log;
class WxService
{
    private $app_id;
    private $pages = [
        0 => '',
        10 => 'pages/index/index'
    ];
    protected $app;

    /**
     * 构造方法
     */
    public function __construct($app_id)
    {
        // 当前用户id
        $this->app_id = $app_id;
        $this->app = AppWx::getApp($this->app_id);
    }

    /**
     * @return mixed
     * env_version要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
     */
    public function getQrCode($user_id, $pageType = 10, $env_version = "release")
    {
        $cache_key = sprintf("wx_qrcode_%d_%d_%s", $user_id, $pageType, $env_version);
        $qrcode = cache($cache_key);
        if ($qrcode) {
            return $qrcode;
        }

        $access_token = $this->app->getAccessToken();
        $token = $access_token->getToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $token;
        $data = [
            'scene' => sprintf("pid=%d", $user_id),
            'page' => $this->pages[$pageType],
            'env_version' => $env_version,
        ];
        $res = curlPost($url, json_encode($data));
        $json = json_decode($res, true);
        if (is_array($json) && $json['errcode'] > 0) {
            Log::info("小程序二维码获取失败：" . $json['errmsg']);
            return false;
        } else {
            //把二进制res转成64位图片数据
            $qrcode = base64_encode($res);
            //拼接上图片头
            $qrcode = 'data:image/png;base64,' . $qrcode;
            cache($cache_key, $qrcode);
            return $qrcode;
        }
    }
}